package com.xiaotao;

import com.alibaba.fastjson.JSON;
import com.xiaotao.entity.GainRecord;
import com.xiaotao.mapper.GainRecordMapper;
import com.xiaotao.vo.TodayEarningVo;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;

@Component // 注入Spring容器
public class DailyRedisUpdateTask implements Job {

    // 注入RedisTemplate（需提前配置Redis连接）
    @Resource
    private RedisTemplate redisTemplateInit;
    @Resource
    private GainRecordMapper gainRecordMapper;

    public void updateRedisData() {
        try {
            System.out.println("开始执行Redis数据更新，时间：" + LocalDateTime.now());
            //每天零点将redis中数据写入数据库
            String jsonStr =(String) redisTemplateInit.opsForValue().get("todayEarnings");
            TodayEarningVo todayEarningVo1 = JSON.parseObject(jsonStr, TodayEarningVo.class);
            GainRecord gainRecord = new GainRecord();
            gainRecord.setDate(new Date());
            gainRecord.setTotalmoney(todayEarningVo1.getTotalMoney());
            gainRecord.setCommissionmoney(todayEarningVo1.getCommissionMoney());
            gainRecordMapper.insert(gainRecord);
            //重置redis数据
            TodayEarningVo todayEarningVo = new TodayEarningVo(new BigDecimal(0), new BigDecimal(0));
            String jsonString = JSON.toJSONString(todayEarningVo);
            redisTemplateInit.opsForValue().set("todayEarnings",jsonString);
        } catch (Exception e) {
            System.err.println("Redis数据更新失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        updateRedisData();
    }
}
